# -*- coding: utf-8 -*-
# (c) 2015 Mikel Arregi - AvanzOSC
# (c) 2015 Oihane Crucelaegui - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

from odoo import _, api, exceptions, fields, models
import odoo.addons.decimal_precision as dp
from odoo.tools.float_utils import float_compare


class masssplitpack(models.TransientModel):
    _name = 'mass.split.pack'

    @api.multi
    @api.constrains('pack_lines')
    def check_qty(self):
        precision_digits = self.env[
            'decimal.precision'].precision_get('Product Unit of Measure')
        pack = self.env['stock.pack.operation'].browse(self.env.context['active_id'])
        for record in self.filtered('pack_lines'):
            if float_compare(record.lines_qty, pack.product_qty,
                             precision_digits=precision_digits) > 0:
                raise exceptions.UserError(
                    _(u'明细数量不得大于原始需求数！'))

    @api.depends('pack_lines', 'pack_lines.qty')
    def _compute_qties(self):
        pack = self.env['stock.pack.operation'].browse(self.env.context['active_id'])

        lines_qty = sum(quant_line.qty for quant_line in self.pack_lines)
        self.lines_qty = lines_qty
        self.pack_qty = pack.product_qty - lines_qty

    name = fields.Char(string=u'名称')
    product_id=fields.Many2one('product.product',u'产品')
    location_id=fields.Many2one('stock.location',u'初始入库位')
    product_qty=fields.Float(u'初始数量')
    lines_qty = fields.Float(
        string=u'分配数', compute='_compute_qties',
        digits=dp.get_precision('Product Unit of Measure'))
    pack_qty = fields.Float(string=u'剩余数', compute='_compute_qties',
                            digits=dp.get_precision('Product Unit of Measure'))
    pack_lines = fields.One2many('mass.split.pack.lines',
                                   'mass_wizard', string=u'拆分的明细')

    @api.multi
    def mass_pack(self):
        pack = self.env['stock.pack.operation'].browse(self.env.context['active_id'])
        # for operation in self:
        #     if float_compare(operation.product_qty, operation.qty_done, precision_rounding=operation.product_uom_id.rounding) == 1:
        #         cpy = operation.copy(default={'qty_done': 0.0, 'product_qty': operation.product_qty - operation.qty_done})
        #         operation.write({'product_qty': operation.qty_done})
        #         operation._copy_remaining_pack_lot_ids(cpy)
        # 拆分
        pack.qty_done=0
        pack.product_qty=self.pack_qty
        for line in self.pack_lines:
            new_pack = pack.copy(default={
                'qty_done': 0.0,
                'product_qty': line.qty,
                'location_id':line.location_id.id,
                'location_dest_id':line.location_dest_id.id,
            })
            pack._copy_remaining_pack_lot_ids(new_pack)
        return {}

    @api.model
    def default_get(self, fields):
        res = super(masssplitpack, self).default_get(fields)
        pack = self.env['stock.pack.operation'].browse(self.env.context['active_id'])
        res.update({'product_id': pack.product_id.id,'location_id': pack.location_id.id,'product_qty': pack.product_qty})
        res = self._convert_to_write(self._convert_to_cache(res))
        return res


class masssplitpackLines(models.TransientModel):
    _name = 'mass.split.pack.lines'
    _rec_name = 'mass_wizard'

    mass_wizard = fields.Many2one(
        comodel_name='mass.split.pack', string='pack', required=True,
        ondelete='cascade')
    location_id = fields.Many2one(comodel_name='stock.location', string=u'来源位置')
    location_dest_id = fields.Many2one(comodel_name='stock.location', string=u'目的位置')
    qty = fields.Float(
        string=u'数量', digits=dp.get_precision('Product Unit of Measure'))
